package com.banciyuan.bcywebview.biz.pc.zone;

import android.os.Build;
import android.os.Bundle;

import com.banciyuan.bcywebview.base.fragment.BaseScrollFragment;
import com.banciyuan.bcywebview.base.util.BaseObserver;
import com.banciyuan.bcywebview.base.util.BaseWatcher;
import com.banciyuan.bcywebview.utils.common.UIUtils;

/**
 * Created by squall on 2016/9/14.
 */
public class BaseLazyScrollFragment extends BaseScrollFragment implements BaseWatcher {

    public boolean isViewInitiated;
    public boolean isVisibleToUser;
    public boolean isDataInitiated;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isViewInitiated = true;
        prepareFetchData();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        prepareFetchData();
        if (isVisibleToUser) {
            BaseObserver.getInstance().addWatcher(BaseLazyScrollFragment.class, this);
        } else {
            BaseObserver.getInstance().removeWatcher(BaseLazyScrollFragment.class);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        BaseObserver.getInstance().removeWatcher(BaseLazyScrollFragment.class);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isVisibleToUser) {
            BaseObserver.getInstance().addWatcher(BaseLazyScrollFragment.class, this);
        }
    }

    public void fetchData() {
    }

    public boolean prepareFetchData() {
        return prepareFetchData(false);
    }

    public boolean prepareFetchData(boolean forceUpdate) {
        if (isVisibleToUser && isViewInitiated && (!isDataInitiated || forceUpdate)) {
            fetchData();
            isDataInitiated = true;
            return true;
        }
        return false;
    }

    public void reFresh() {

    }

    public int getOffset() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            return UIUtils.dip2px(20, getActivity());
        } else {
            return 0;
        }
    }

    @Override
    public void onEventHappen(int eventCode, String message, Object object) {
        if (eventCode == BaseObserver.REFRESH_PERSON) {
            reFresh();
        }
    }
}
